<?php

namespace app\apisell\controller\xcx;

use app\apisell\controller\admin\Exception;
use app\BaseController;
use app\common\utils\Res;
use DateInterval;
use DateTime;
use DateTimeZone;
use think\facade\Db;
use think\facade\Log;

class User extends BaseController
{

    /**
     * 客户列表
     */
    public function getUserList()
    {
        $param = $this->request->param();
        $size = $param['pageSize'] ? $param['pageSize'] : 10;  //每页显示条数
        $page = $param['page'] ? $param['page'] : 1;  //当前页数
        $start = ($page - 1) * $size;
        $nickname = $param['nickname'] ? $param['nickname'] : false;  //用户昵称
        $ctime = $param['ctime'] ? $param['ctime'] : false;  //查看时间
        $number = $param['number'] ? $param['number'] : false;  //查看次数
        $money = $param['money'] ? $param['money'] : false;  //消费总金额
        $userId =  $this->request->id;//获取用户id
        $wheredata = " and pu.popu_id = ".$userId;
//        $wheredata = " and u.id = 1";
        $username = '';
        $orderby = '';
        if ($nickname) {
            $username = " and u.nickname like '%".$nickname. "%' " ;
        }
        if ($ctime) {
            $orderby  = " order by c.create_time ".$ctime;
        }
        if ($number) {
            $orderby  = " order by ec.childnumber ".$number;
        }
        if ($money) {
            $orderby  = " order by o.money ".$money;
        }
        /*
        $sql = "select u.*,s.title,s.image,ec.childnumber,o.money,c.create_time as ctime from xh_sell_user u
            left join xh_sell_popu_user_control pu on u.id = pu.user_id
            left join (select * from xh_sell_goods_exposure_child GROUP BY user_id ORDER BY create_time desc) c on u.id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_goods_exposure_child GROUP BY user_id) ec on u.id = ec.user_id
            left join (select user_id, sum(payer_total) as money from xh_sell_order) o on u.id = o.user_id
            left join xh_sell_order_goods s on c.goods_id = s.id where 1=1 ". $wheredata . $username . $orderby ." limit :start, :limit";
        */
        $sql = "select u.*,s.title,s.image,ec.childnumber,o.money,c.`time` as ctime from xh_sell_user u
            left join xh_sell_popu_user_control pu on u.id = pu.user_id
            left join (select * from xh_sell_num_desc GROUP BY user_id ORDER BY `time` desc) c on u.id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_num_desc GROUP BY user_id) ec on u.id = ec.user_id
            left join (select user_id, sum(payer_total) as money from xh_sell_order) o on u.id = o.user_id
            left join xh_sell_order_goods s on c.goods_id = s.id where 1=1 ". $wheredata . $username . $orderby ." limit :start, :limit";
        $user = Db::query($sql,['start' => $start, 'limit' => $size]);

        /*
        $sqlcount = "select u.*,s.title,s.image,ec.childnumber,o.money,c.create_time as ctime from xh_sell_user u
            left join xh_sell_popu_user_control pu on u.id = pu.user_id
            left join (select * from xh_sell_goods_exposure_child GROUP BY user_id ORDER BY create_time desc) c on u.id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_goods_exposure_child GROUP BY user_id) ec on u.id = ec.user_id
            left join (select user_id, sum(payer_total) as money from xh_sell_order) o on u.id = o.user_id
            left join xh_sell_order_goods s on c.goods_id = s.id where 1=1 ". $wheredata . $username . $orderby ;
        */
        $sqlcount = "select u.*,s.title,s.image,ec.childnumber,o.money,c.`time` as ctime from xh_sell_user u
            left join xh_sell_popu_user_control pu on u.id = pu.user_id
            left join (select * from xh_sell_num_desc GROUP BY user_id ORDER BY `time` desc) c on u.id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_num_desc GROUP BY user_id) ec on u.id = ec.user_id
            left join (select user_id, sum(payer_total) as money from xh_sell_order) o on u.id = o.user_id
            left join xh_sell_order_goods s on c.goods_id = s.id where 1=1 ". $wheredata . $username . $orderby ;
        $count = Db::query($sqlcount);
        $data = [
           'list' => $user,
           'total' => count($count)
        ];
        return Res::ok($data);
    }

    public function userInfo() 
    {
        $param = $this->request->param();
        $userId = $param['userId'];
        $time = $param['time'];
        //顶部客户信息
        $user = Db::table('xh_sell_user')->where(['id' => $userId])->find();
        
        //中部数据统计
        /*
        $sql = "select a.user_id, b.sumprice, c.pay_time, d.childnumber, a.sumpayer from (select user_id, SUM(payer_total) as sumpayer from xh_sell_order where state = 5) a
            left join (select user_id, SUM(price) as sumprice from xh_sell_refund where state = 3) b on a.user_id = b.user_id
            left join (select user_id, pay_time from xh_sell_order where state = 2 ORDER BY pay_time LIMIT 1) c on a.user_id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_goods_exposure_child GROUP BY user_id) d on a.user_id = d.user_id
            where a.user_id =". $userId;
        */
        $sql = "select a.user_id, b.sumprice, c.pay_time, d.childnumber, a.sumpayer from (select user_id, SUM(payer_total) as sumpayer from xh_sell_order where state = 5) a
            left join (select user_id, SUM(price) as sumprice from xh_sell_refund where state = 3) b on a.user_id = b.user_id
            left join (select user_id, pay_time from xh_sell_order where state = 2 ORDER BY pay_time LIMIT 1) c on a.user_id = c.user_id
            left join (select user_id, count(id) as childnumber from xh_sell_num_desc GROUP BY user_id) d on a.user_id = d.user_id
            where a.user_id =". $userId;
        $countData = Db::query($sql);
        
        //底部数据  生命周期
        $order = Db::table('xh_sell_order')->alias('o')
            ->field('o.*, g.title')
            ->leftJoin('xh_sell_order_goods g','o.id = g.order_id')
            ->where(['o.user_id' => $userId])
            ->select()->toArray();
        $createOrder = array();
        $payOrder = array();
        $serviceOrder = array();
        $rfOrder = array();
        $childOrder = array();
        $smzq = array();
        if ($order) {
            foreach ($order as $k => $v) {
                //创建订单
                if ($v['state'] == 1 && strpos($v['create_time'], $time) !== false) {
                    $a['title'] = "创建了订单《".$v['title']."》";
                    $a['date'] = $v['create_time'];
//                    $createOrder[$v['create_time']] = "创建了订单《".$v['title']."》";
//                    $createOrder[$v['create_time']] = $a;
                    $smzq[$v['create_time']] = $a;
                    unset($a);
                }
                //支付成功
                if ($v['pay_time'] && strpos($v['pay_time'], $time) !== false) {
                    $a['title'] = "支付成功《".$v['title']."》";
                    $a['date'] = $v['pay_time'];
//                    $payOrder[$v['pay_time']] = $a;
                    $smzq[$v['pay_time']] = $a;
                    unset($a);
                }
            }
        }
        
        $refundOrder = Db::table('xh_sell_refund')->alias('r')
            ->field('r.*, g.title')
            ->leftJoin('xh_sell_order_goods g','r.order_id = g.order_id')
            ->where(['r.user_id' => $userId])
            ->select()->toArray();
        if ($refundOrder) {
            foreach ($refundOrder as $key => $value) {
                //申请售后
                if ($value['state'] == 0 && strpos($value['create_time'], $time) !== false) {
                    $a['title'] = "申请售后《".$value['title']."》";
                    $a['date'] = $value['create_time'];
//                    $serviceOrder[$value['create_time']] = "申请售后《".$value['title']."》";
//                    $serviceOrder[$value['create_time']] = $a;
                    $smzq[$value['create_time']] = $a;
                    unset($a);
                }
                //退款成功
                if ($value['state'] == 3 && strpos($value['agreetime'], $time) !== false) {
                    $a['title'] = "退款成功《".$value['title']."》";
                    $a['date'] = $value['agreetime'];
//                    $rfOrder[$value['agreetime']] = "退款成功《".$value['title']."》";
//                    $rfOrder[$value['agreetime']] = $a;
                    $smzq[$value['agreetime']] = $a;
                    unset($a);
                }
            }
        }
        
        /*
        $child = Db::table('xh_sell_goods_exposure_child')->where(['user_id' => $userId])->select()->toArray();
        if ($child) {
            foreach ($child as $item) {
                if (strpos($item['create_time'], $time) !== false) {
                    $a['title'] = "浏览了《".$item['goods_name']."》";
                    $a['date'] = $item['create_time'];
//                    $childOrder[$item['create_time']] = "浏览了《".$item['goods_name']."》";
//                    $childOrder[$item['create_time']] = $a;
                    $smzq[$item['create_time']] = $a;
                    unset($a);
                }
            }
        }
        */
        
        $child = Db::table('xh_sell_num_desc')->alias('d')
            ->leftJoin('xh_sell_goods g', 'd.goods_id = g.id')
            ->field('d.*, g.name as goods_name')
            ->where('d.user_id', $userId)
            ->select()->toArray();
        if ($child) {
            foreach ($child as $item) {
                if (strpos($item['time'], $time) !== false) {
                    $a['title'] = "浏览了《".$item['goods_name']."》";
                    $a['date'] = $item['time'];
                    $smzq[$item['time']] = $a;
                    unset($a);
                }
            }
        }

//        $smzq = array_merge($createOrder,$payOrder,$serviceOrder,$rfOrder,$childOrder);
        krsort($smzq);
        $desc = array();
        foreach ($smzq as $k => $v) {
            $desc[] = $v;
        }
        //订单列表
        $data = [
            'user' => $user,
            'countData' => $countData,
            'smzq' => $desc,
            'order' => $order,
        ];
        return Res::ok($data);
    }
    /**
     * 冻结价格结算函数
     *
     * 本函数用于处理特定状态下订单的冻结资金结算操作具体功能包括：
     * 1. 查询所有状态为5且结算时间小于当前时间的订单
     * 2. 遍历这些订单，对每个订单根据收益级别更新用户的冻结资金和待结算资金
     * 3. 如果更新过程中遇到任何异常，记录错误日志并返回错误信息
     */
    public function freezePrice()
    {
        // 获取当前时间
        $times = date('Y-m-d H:i:s',time());
        
        try {
            // 查询需要处理的订单
            $order = Db::table('xh_sell_order')
                ->where('state','in','2,3,5')
                ->whereTime('settle_time','<',$times)
                ->field('earnings_level_one,earnings_level_two,belongs_popu_user_id,order_no,popu_id')
                ->limit(10)
                ->select()
                ->toArray(); 
            
            // 遍历订单进行处理
            foreach ($order as  $val){
                $popuId = (int)$val['belongs_popu_user_id'];
                $earningsLevelOne = $val['earnings_level_one'];
                $earningsLevelTwo = $val['earnings_level_two'];
                
                // 根据收益级别更新用户资金
                if ($earningsLevelOne > 0){
                    //查找上一级
                    $popu_user_id = Db::table('xh_sell_popu_user')
                        ->where('id',$popuId)
                        ->field('popu_user_id,invite_user_id')
                        ->find();
                    // 减少冻结资金，增加待结算资金
                    Db::table('xh_sell_user')
                        ->where('id',$popu_user_id['popu_user_id'])
                        ->dec('money_freeze',$earningsLevelOne)
                        ->update();
                    $resInfo = Db::table('xh_sell_user')
                        ->where('id',$popu_user_id['popu_user_id'])
                        ->inc('money_pay_await',$earningsLevelOne)
                        ->update();
                    if ($resInfo){
                        Db::table('xh_sell_order')->where('order_no',$val['order_no'])->update(['settle'=>1]);
                    }
                    
                    $user = Db::table('xh_sell_user')
                        ->where('id',$popu_user_id['popu_user_id'])
                        ->field('money_pay_await,money_freeze')
                        ->find();
                    // 构建日志描述
                    $desc = '【'.$times.'】订单【'.$val['order_no'].'】价格【'.$val['money_freeze'].'】推广ID【'.$val['popu_id'].'】收益【'.$earningsLevelOne.'】元';
                    // 构建变更详情数组
                    $change_json = [
                        [
                            'field' => 'money_freeze',
                            'former' => $user['money_freeze'],
                            'after' => $earningsLevelOne
                        ],
                        [
                            'field' => 'money_pay_await',
                            'former' => $user['money_pay_await'],
                            'after' => $earningsLevelOne
                        ],
                    ];
                    // 构建日志数据
                    $data = [
                        'user_id'=>$popu_user_id['popu_user_id'],
                        'type'=>'订单收益',
                        'desc'=>$desc,
                        'remark'=> '一级分佣',
                        'change_json'=> json_encode($change_json),
                        'change_money'=>$earningsLevelOne,
                        'change_time'=>$times,
                        'order_no'=>$val['order_no'],
                    ];

                    // 插入日志记录
                    Db::table('xh_sell_user_money_log')->insert($data);

                }
                if ($earningsLevelTwo > 0){
                    // 同上，处理第二级别的收益
                    //查找上上级
                    $inviteUserId = Db::table('xh_sell_popu_user')
                        ->where('id',$popu_user_id['invite_user_id'])
                        ->value('id');
                    Db::table('xh_sell_user')
                        ->where('id',$inviteUserId)
                        ->dec('money_freeze',$earningsLevelTwo)
                        ->update();
                    $payInfo = Db::table('xh_sell_user')
                        ->where('id',$inviteUserId)
                        ->inc('money_pay_await',$earningsLevelTwo)
                        ->update();
                    if ($payInfo){
                        Db::table('xh_sell_order')->where('order_no',$val['order_no'])->update(['settle'=>1]);
                    }
                    
                    $userInfo = Db::table('xh_sell_user')
                        ->where('id',$inviteUserId)
                        ->field('money_pay_await,money_freeze')
                        ->find();
                    $desc = '【'.$times.'】订单【'.$val['order_no'].'】价格【'.$val['money_pay_await'].'】推广ID【'.$val['popu_id'].'】收益【'.$earningsLevelTwo.'】元';
                    // 构建变更详情数组
                    $change_json = [
                        [
                            'field' => 'money_freeze',
                            'former' => $userInfo['money_freeze'],
                            'after' => $earningsLevelTwo
                        ],
                        [
                            'field' => 'money_pay_await',
                            'former' => $userInfo['money_pay_await'],
                            'after' => $earningsLevelTwo
                        ],
                    ];
                    // 构建日志数据
                    $data = [
                        'user_id'=>$popu_user_id['popu_user_id'],
                        'type'=>'订单收益',
                        'desc'=>$desc,
                        'remark'=> '二级级分佣',
                        'change_json'=> json_encode($change_json),
                        'change_money'=>$earningsLevelTwo,
                        'change_time'=>$times,
                        'order_no'=>$val['order_no'],
                    ];

                    // 插入日志记录
                    Db::table('xh_sell_user_money_log')->insert($data);
                }
            }
            // 更新成功
            return Res::ok('更新成功');
        
        } catch (\Exception $e) {
            // 记录日志
            Log::error('Error in freezePrice: ' . $e->getMessage());
            // 返回错误信息
            return Res::error('更新失败'.$e->getMessage());
        }
    }
    public function getOrderCount()
    {
        $user_id =  $this->request->id;//获取用户id
        if (!$user_id){
            return Res::error('参数错误');
        }
        $totalCount = Db::table('xh_sell_order')->where('user_id',$user_id)->count();
        $unpaid = Db::table('xh_sell_order')->where('user_id',$user_id)->where('state',1)->count();
        $paid = Db::table('xh_sell_order')->where('user_id',$user_id)->where('state','in',[2,3])->count();
        $saleInfo = Db::table('xh_sell_order')->where('user_id',$user_id)->where('state',4)->count();
        return Res::ok(['totalCount'=>$totalCount,'unpaid'=>$unpaid,'paid'=>$paid,'saleInfo'=>$saleInfo]);
    }

    
}